<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\RegisterRequest;
use App\Http\Requests\SendEmailRequest;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\AuthorizationRequest;
use Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;

class AuthorizationsController extends Controller
{
    public function store(AuthorizationRequest $request)
    {
        $username = $request->username;

        filter_var($username, FILTER_VALIDATE_EMAIL) ?
            $credentials['email'] = $username :
            $credentials['name'] = $username;

        $credentials['password'] = $request->password;

        if (!$token = \Auth::guard('api')->attempt($credentials)) {
            return $this->response->errorUnauthorized('用户名或密码错误');
        }

        return $this->respondWithToken($token)->setStatusCode(201);

    }

    public function register(RegisterRequest $request)
    {
        $smsPayload = \json_decode(Cache::get($request->email_key), true);
        if(!$smsPayload) {
            return $this->response->array(responseJson(4001,$smsPayload,'email_key 没有找到'));
        }
        $email = array_get($smsPayload, 'payload.email');
        if($email != $request->email || $smsPayload['code'] != $request->email_value) {
            \Log::error('Error in mailbox or verification code ', ['payload' => $smsPayload, 'key' => $request->email_key]);
            return $this->response->array(responseJson(4001,$smsPayload,'非法注册'));
        }
        return User::create([
            'email'=>$email,'name'=>$request->name,'password'=>bcrypt($request->password)
        ]);
    }

    public function sendEmail(SendEmailRequest $request)
    {
        $key = str_random(100);
        $payload = ['count'=>0,'email'=>$request->email];
        $expiresAt = 5;
        $code = $this->code($request->email);

        Cache::put($key, \json_encode(['code' => $code, 'payload' => $payload]), $expiresAt);
        return $this->response->array(['email_key'=>$key]);
    }

    public function code($email)
    {
        // todo :具体实现
        $code = rand(100000, 999999);
        Mail::raw('邮箱验证码是：'.$code."五分钟内有效！",function ($message) use ($email) {
            $message->subject('Exgain');
            $message->to($email);
        });
        return $code;
    }
    protected function respondWithToken($token)
    {
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard('api')->factory()->getTTL() * 60
        ]);
    }

    public function update()
    {
        $token = Auth::guard('api')->refresh();
        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        Auth::guard('api')->logout();
        return $this->response->noContent();
    }
}
